package com.samphanie.auiu.biz.goods

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.launcher.ARouter
import com.samphanie.auiu.R
import com.samphanie.auiu.common.ui.component.AuiuAbsListFragment
import com.samphanie.auiu.fragment.home.GoodsItem
import com.samphanie.auiu.http.api.goodsApiService
import com.samphanie.auiu.library.restful.AuiuCallback
import com.samphanie.auiu.library.restful.AuiuResponse
import com.samphanie.auiu.model.GoodsList
import com.samphanie.auiu.route.AuiuRoute

class GoodsListFragment : AuiuAbsListFragment() {

    @JvmField
    @Autowired
    var cateId: String = ""

    @JvmField
    @Autowired
    var subCateId: String = ""

    companion object {
        fun newInstance(cateId: String, subCateId: String) : Fragment {
            val args = Bundle()
            args.putString("cateId", cateId)
            args.putString("subCateId", subCateId)
            val fragment = GoodsListFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initialize(savedInstanceState: Bundle?) {
        super.initialize(savedInstanceState)
        AuiuRoute.inject(this)
        enableLoadMore { loadData() }

        loadData()
    }

    override fun onRefresh() {
        super.onRefresh()
        loadData()
    }

    private fun loadData() {
        goodsApiService().queryCategoryGoodsList(cateId, subCateId, pageNum, 10)
            .enqueue(object : AuiuCallback<GoodsList> {
                override fun onSuccess(response: AuiuResponse<GoodsList>) {
                    if (response.successful() && response.data != null) {
                        onQueryCategoryGoodsList(response.data!!)
                    } else {
                        finishRefresh(null)
                    }
                }

                override fun onFailed(throwable: Throwable) {
                    finishRefresh(null)
                }

            })
    }

    private fun onQueryCategoryGoodsList(data: GoodsList) {
        val dataItems = mutableListOf<GoodsItem>()
        for (goodsModel in data.list) {
            val goodsItem = GoodsItem(goodsModel, false)
            dataItems.add(goodsItem)
        }
        finishRefresh(dataItems)
    }

    override fun createLayoutManager(): RecyclerView.LayoutManager {
        return GridLayoutManager(context, 2)
    }

}